<?php
class ModelSaleNewsletter extends Model {
	public function addNewsletter($data) {
		$this->db->query("INSERT INTO " . DB_PREFIX . "newsletter SET firstname = '" . $this->db->escape($data['firstname']) . "', newsletter_id = '" . $this->db->escape($data['newsletter_id']) . "', lastname = '" . $this->db->escape(strip_tags($data['lastname'])) . "' , email = '" . $this->db->escape(strip_tags($data['email'])) . "', status = '" . (int)$data['status'] . "', date_added = NOW()");
	}
	
	public function editNewsletter($newsletter_id, $data) {
		$this->db->query("UPDATE " . DB_PREFIX . "newsletter SET firstname = '" . $this->db->escape($data['firstname']) . "', newsletter_id = '" . $this->db->escape($data['newsletter_id']) . "', lastname = '" . $this->db->escape(strip_tags($data['lastname'])) . "' , email = '" . $this->db->escape(strip_tags($data['email'])) . "', status = '" . (int)$data['status'] . "', date_added = NOW() WHERE newsletter_id = '" . (int)$newsletter_id . "'");
	}
	
	public function deleteNewsletter($newsletter_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "newsletter WHERE newsletter_id = '" . (int)$newsletter_id . "'");
	}
	
	public function getNewsletter($newsletter_id) {
		$query = $this->db->query("SELECT r.* FROM " . DB_PREFIX . "newsletter r WHERE r.newsletter_id = '" . (int)$newsletter_id . "'");
		
		return $query->row;
	}

	public function getNewsletters($data = array()) {
		$sql = "SELECT r.firstname,r.lastname,r.newsletter_id, r.status, r.date_added,r.email FROM " . DB_PREFIX . "newsletter r ";																																					  
		
		$sort_data = array(
			'r.firstname',
			'r.lastname',
			'r.email',
			'r.status',
			'r.date_added'
		);	
			
		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];	
		} else {
			$sql .= " ORDER BY r.date_added";	
		}
			
		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}
		
		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}			

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}	
			
			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}																																							  
																																							  
		$query = $this->db->query($sql);																																				
		
		return $query->rows;	
	}
	
	public function getTotalNewsletters() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "newsletter");
		
		return $query->row['total'];
	}
	
	public function getTotalNewslettersAwaitingApproval() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "newsletter WHERE status = '0'");
		
		return $query->row['total'];
	}	
}
?>